#-------------------------------------------------------------------------------
# Name:        run_protein_test
# Purpose:     This script takes from stdin (or argv[1] file) json-representation of dict for
#              mappanalysis.ProgramVariables created by generate_json_*.py script
#              and run mapp analysis for given values.
#              Mapp output is written to the stdout.
#
# Author:      Bc. Ondrej Pelikan
#
# Created:     23.04.2013
#-------------------------------------------------------------------------------

import fileinput
import json
#from utils import addDirToSysPath
#addDirToSysPath("../") #relative path to parent folder of mappanalysis package
import mappanalysis
import logging
import os


logfiledir = "./logs/"
logger = None


def main():
    #parse ProgramVariables from file or stdin
    jsonstr = ""
    for line in fileinput.input():
        jsonstr += line

    d = json.loads(jsonstr)
    progVars = mappanalysis.ProgramVariables(d["sequence"], d["mutations"])
    if "database" in d:
        progVars.database_type = d["database"]
    if "error" in d:
        progVars.error = d["error"]
    if "tree_method" in d:
        progVars.treeMethod = d["tree_method"]
    if "inclusion_ethresh" in d:
        progVars.inclusion_ethresh = str(d["inclusion_ethresh"])
    if "num_iterations" in d:
        progVars.num_iterations = str(d["num_iterations"])
    if "num_alignments" in d:
        progVars.num_alignments = str(d["num_alignments"])

    #set logging
    logging.basicConfig(filename=os.path.join(logfiledir, d["filename"]+'.log'),
                format='%(asctime)s %(levelname)s:%(message)s',
                datefmt='%H:%M:%S',
                filemode='w',
                level=logging.DEBUG)
    global logger
    logger = logging.getLogger(__name__)
    logger.info("Starting " + d["filename"] + " analysis.")

    #run mapp analysis
    mappoutput = mappanalysis.runPrograms(progVars)

    logger.info("Ending " + d["filename"] + " analysis.")
    print("\n".join(mappoutput) + "\n")



if __name__ == '__main__':
    main()
